/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal/allocator.h"
#include "dal_fastdds/utils/EntityMappingManager.hpp"
#include "dal_fastdds/listener_impl/DataWriterListenerImplDbhExtend.hpp"

DataWriterListenerImplDbhExtend::DataWriterListenerImplDbhExtend(
    dal_datawriter_listener_callbacks_t callbacks, StatusMask& mask)
    : DataWriterListenerImpl(callbacks), mask_(mask)
{
}

DataWriterListenerImplDbhExtend::~DataWriterListenerImplDbhExtend() {}

void DataWriterListenerImplDbhExtend::on_publication_matched(DataWriter* writer,
                                                             const PublicationMatchedStatus& info)
{
    matched_readers_cnt_map_.Update(writer->guid(), info.current_count);

    if (!mask_.is_active(StatusMask::subscription_matched()))
        return;

    if (callbacks_.on_publication_matched == nullptr)
        return;

    dal_datawriter_t* dal_writer = EntityMappingGetDataWriter(writer);
    if (!dal_writer) {
        dal_datawriter_t* dal_writer_tmp = dal_datawriter_allocate();
        dal_writer = EntityMappingGetOrAddDataWriter(writer, dal_writer_tmp);
        if (dal_writer_tmp != dal_writer) {
            dal_datawriter_free(dal_writer_tmp);
        }
    }

    dal_publication_matched_status_t dal_status;
    StatusConverter::GetInstance()->ConvertPublicationMatchedStatusFromFastddsToDal(&info,
                                                                                    &dal_status);

    void* data = callbacks_.data_;
    (callbacks_.on_publication_matched)(dal_writer, &dal_status, data);
}
